package top.jnaw.test.service;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.util.ArrayList;
import java.util.List;
import top.jnaw.test.model.Permissions;
import top.jnaw.test.model.Roles;
import top.jnaw.test.model.RolesPermissions;
import top.jnaw.test.model.UserRoles;

/**
 * Permissions 管理
 * 描述：
 */
public class RoleService {

	//private static final Log log = Log.getLog(PermissionsService.class);
  public static final Roles dao = new Roles().dao();

  public static List<Roles> getRoleList(String cnname) {
    String sql = " SELECT  * FROM roles ";
    if (StrKit.notBlank(cnname)){
      sql+=" WHERE role_cn_name LIKE '"+cnname+"' ";
    }
    return dao.find(sql);
  }

  public static List<Permissions> getPermissionsList(String name) {
    String sql = " SELECT * FROM permissions ";
    if (StrKit.notBlank(name)){
      sql+=" WHERE permissions_name LIKE '"+name+"' ";
    }
    return Permissions.dao.find(sql);
  }

  /**
   * 根据用户名和权限，去判断有没有该权限
   * @param username
   * @param per
   * @return
   */
  public boolean hasPreAndUser(String username, String per) {
    List<Record> list = new ArrayList<>();
    String sql = "SELECT "
        + "  rp.id, "
        + "  rp.role_name, "
        + "  rp.permission, "
        + "  ur.username "
        + " FROM roles_permissions rp LEFT JOIN user_roles ur ON ur.role_name = rp.role_name "
        + " WHERE ur.username = ? AND rp.permission = ? ";
    list = Db.find(sql, username, per);
    if (list.size() > 0) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * 删除某个角色的所有权限
   * @param rolename
   * @return
   */
  public static boolean delByRolename(String rolename){
    String sql = "DELETE FROM roles_permissions WHERE role_name = ?";
    int a = Db.update(sql,rolename);
    if (a>0){
      return true;
    }
    return false;
  }

  /**
   * 角色的所有权限
   * @param role
   * @return
   */
  public static List<RolesPermissions> getListByRole(String role) {
    String sql = " SELECT rp.*,p.permissions_name FROM roles_permissions rp LEFT JOIN permissions p ON rp.permission =p.permissions WHERE rp.role_name = ? ";
    return  RolesPermissions.dao.find(sql,role);
  }


  //查询用户的角色
  public List<UserRoles> hasRole(String username) {
    String sql = "select * from user_roles where  username = ?";
    List<UserRoles> list = UserRoles.dao.find(sql, username);
    return list;
  }


  //给用户删除角色名
  public boolean rmRoleByUsername(String username) {
    String sql = "DELETE FROM user_roles WHERE username = ?";
    if (Db.update(sql, username) > 0) {
      return true;
    }
    return false;
  }

}